import React, { Component, Fragment } from 'react';
import StandardTable from '@/components/StandardTable';
import { Icon, Form, Input, Modal, Select, Row, Col, Upload, DatePicker } from 'antd';
import { connect } from 'dva';
import styles from '@/pages/Info.less';
import moment from 'moment';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import AntdInput from '@/components/AntdInput';
import AdSelect from '@/components/AdSelect';

const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { Option } = Select;
const dateFormat = 'YYYY-MM-DD';
const confirm = Modal.confirm;

@connect(({ upkeep, loading, common }) => ({
  upkeep,
  loading: loading.models.upkeep,
  dictObject: common.dictObject,
}))
@Form.create()
export default class UpkeepInfo extends Component {
  state = {
    selectedRows: [],
  };
  componentDidMount() {
    const { dispatch, onRef } = this.props;
    // 查询字典：
    //类型：
    dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'upkeep_details_type' },
    });
    onRef && onRef(this);
  }
  columns = [
    {
      title: '名称',
      dataIndex: 'name',
      render: (text, record) =>
        this.props.type === 'list' && !this.props.disabled ? (
          <AdButton
            mode="a"
            onClick={() => this.showDetail(record.id)}
            text={text}
            code={codes.showDetail}
          />
        ) : (
          <span>{text}</span>
        ),
    },
    {
      title: '编号',
      dataIndex: 'number',
    },
    {
      title: '类型',
      dataIndex: 'type',
      render: text => (
        <AdSelect
          onlyRead={true}
          value={text}
          data={this.props.dictObject['upkeep_details_type']}
        />
      ),
    },

    {
      title: '数量',
      dataIndex: 'quantity',
    },
    {
      title: '总金额',
      dataIndex: 'totalFee',
      render: text => {
        return <span>{text && Number(text) !== 0 ? Number(text).toFixed(2) : ''}</span>;
      },
    },
    {
      title: '单价',
      dataIndex: 'upkeepTime',
      render: (text, record) => (
        <span>{(Number(record.totalFee) / Number(record.quantity)).toFixed(2)}</span>
      ),
    },
    {
      title: '品牌',
      dataIndex: 'brand',
    },
    {
      title: '质保期',
      dataIndex: 'assurancePeriod',
    },
    {
      title: '型号',
      dataIndex: 'upkeepModel',
    },
  ];
  state = {
    id: 0,
  };

  showDetail = id => {
    const { showDetail, dispatch } = this.props;
    if (showDetail) showDetail();
    this.setState({ detailId: id });
    dispatch({
      type: 'upkeep/upkeepInfoDetail',
      payload: { id },
    });
  };

  handleOk = () => {
    const { form, dispatch, id } = this.props;
    const { detailId } = this.state;
    form.validateFields((err, value) => {
      if (err) {
        return;
      }
      const { assurancePeriod, ...values } = value;
      if (assurancePeriod) {
        values.assurancePeriod = moment(assurancePeriod).format(dateFormat);
      }
      values.upkeepId = id;
      if (detailId) {
        values.id = detailId;
      }
      dispatch({
        type: 'upkeep/upkeepInfoOperate',
        payload: values,
        callback: res => {
          this.dispatchCall(res);
        },
      });
    });
  };

  dispatchCall = res => {
    const { form, dispatch, id } = this.props;
    dispatch({
      type: 'upkeep/upkeepInfoList',
      payload: { id },
    });
    dispatch({
      type: 'upkeep/upkeepDetail',
      payload: { id },
    });
    form.resetFields();
    res && this.handleCancel();
  };

  handleSelectRows = selectedRows => {
    const { selected } = this.props;
    this.setState({
      selectedRows,
    });
    selected(selectedRows);
  };

  //删除明细
  removeRecord = () => {
    const { dispatch, id } = this.props;
    const { visible, formValues, selectedRows } = this.state;
    confirm({
      title: '确定要删除这条数据吗？',
      content: ' ',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'upkeep/deleteUpkeepInfo',
          payload: { ids: selectedRows.map(v => v.id) },
          callback: () => {
            this.dispatchCall();
            const { selected } = this.props;
            this.setState({
              selectedRows: [],
            });
            selected([]);
          },
        });
      },
    });
  };

  handleCancel = () => {
    const { handleCancel } = this.props;
    this.setState({
      detailId: '',
    });
    handleCancel();
  };

  render() {
    const {
      loading,
      data,
      change,
      visible,
      form: { getFieldDecorator },
      id,
      type,
      upkeep: {},
      dictObject,
    } = this.props;
    const { detailId, selectedRows } = this.state;
    const infoDetail = detailId ? this.props.upkeep.infoDetail : {};

    return (
      <Fragment>
        <StandardTable
          disabledRowSelected={type == 'detail' ? true : false}
          selectedRows={selectedRows}
          onSelectRow={this.handleSelectRows}
          scrollX={500}
          loading={loading}
          data={data}
          scrollY={200}
          columns={this.columns}
          onPaginationChange={change}
        />
        {visible && (
          <Modal
            title={detailId ? '编辑明细' : '新增明细'}
            visible={visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            width={620}
            style={{ top: 20 }}
            destroyOnClose={true}
          >
            <div className={styles.tableListForm}>
              <Form layout="inline">
                <Row gutter={{ md: 4, lg: 12, xl: 24 }}>
                  <Col md={{ span: 12 }} sm={24}>
                    <Form.Item label="类型">
                      {getFieldDecorator('type', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: infoDetail.type || undefined,
                      })(
                        <Select placeholder="请选择" allowClear={true}>
                          {dictObject['upkeep_details_type'] &&
                            dictObject['upkeep_details_type'].map(item => (
                              <Option key={item.code}>{item.value}</Option>
                            ))}
                        </Select>
                      )}
                    </Form.Item>
                  </Col>
                  <Col md={{ span: 12 }} sm={24}>
                    <Form.Item label="名称">
                      {getFieldDecorator('name', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: infoDetail.name || '',
                      })(<Input placeholder="请输入" />)}
                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={{ md: 4, lg: 12, xl: 24 }}>
                  <Col md={{ span: 12 }} sm={24}>
                    <Form.Item label="数量">
                      {getFieldDecorator('quantity', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: infoDetail.quantity || '',
                      })(<Input placeholder="请输入" />)}
                    </Form.Item>
                  </Col>
                  <Col md={{ span: 12 }} sm={24}>
                    <Form.Item label="总金额">
                      {getFieldDecorator('totalFee', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: infoDetail.totalFee
                          ? Number(infoDetail.totalFee).toFixed(2)
                          : '',
                      })(
                        <AntdInput
                          mode="money"
                          label="金额"
                          placeholder="长度不超过18位可保留两位小数"
                          // addonBefore={prefixSelector()}
                        />
                      )}
                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={{ md: 4, lg: 12, xl: 24 }}>
                  <Col md={{ span: 12 }} sm={24}>
                    <Form.Item label="品牌">
                      {getFieldDecorator('brand', {
                        initialValue: infoDetail.brand || '',
                      })(<Input placeholder="请输入" />)}
                    </Form.Item>
                  </Col>
                  <Col md={{ span: 12 }} sm={24}>
                    <Form.Item label="编号">
                      {getFieldDecorator('number', {
                        initialValue: infoDetail.number || '',
                      })(<Input placeholder="请输入" />)}
                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={{ md: 4, lg: 12, xl: 24 }}>
                  <Col md={{ span: 12 }} sm={24}>
                    <Form.Item label="质保期">
                      {getFieldDecorator('assurancePeriod', {
                        initialValue:
                          infoDetail && infoDetail.assurancePeriod
                            ? moment(infoDetail.assurancePeriod, dateFormat)
                            : null,
                      })(<DatePicker style={{ width: '100%' }} />)}
                    </Form.Item>
                  </Col>
                  <Col md={{ span: 12 }} sm={24}>
                    <Form.Item label="型号">
                      {getFieldDecorator('upkeepModel', {
                        initialValue: infoDetail.upkeepModel || '',
                      })(<Input placeholder="请输入" />)}
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </div>
          </Modal>
        )}
      </Fragment>
    );
  }
}
